package com.yy.yyui.anime
{
	import com.siku.manor.view.component.IDataContainer;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class LoopFrameAnimation extends Sprite implements IDataContainer
	{
		private var _data:Object;
		public var _frames:Array;
		private var pFrame:uint;
		private var timer:Timer;		
		public function LoopFrameAnimation(frames:Array,frameRateSecond:Object=null){
			//TODO: implement function
			super();
			var i:int,l:int;
			pFrame = 0;
			this._frames = frames;
			if(this.frames!=null){
				for(i=0,l=this.frames.length;i<l;i++){
					this.frames[i].visible = false;
					this.addChild(this.frames[i]);
				}
				this.frames[0].visible = true;
			}
			if(frameRateSecond!=null){
				timer = new Timer(Number(frameRateSecond));
				timer.addEventListener(TimerEvent.TIMER,timerHandler);
			}
		}
		
		public function get frames():Array{return this._frames;}
		
		public function set frames(value:Array):void{
			var i:int,l:int;
			var visibleFrame:Object;
			for(i=0,l=value.length;i<l;i++){
				var oldFrame:Object = this.frames[i];
				if(oldFrame!=null){
					value[i].visible = oldFrame.visible;
				}
				if(value[i].visible){
					visibleFrame = i;
				}
			}
			if(visibleFrame==null){
				value[0].visible = true;
				visibleFrame = 0;
			}
			this.pFrame = visibleFrame as int;
			for(i=0,l=this.frames.length;i<l;i++){
				if(this.contains(this.frames[i])){
					this.removeChild(this.frames[i]);
				}
			}
			for(i=0,l=value.length;i<l;i++){
				this.addChild(value[i]);
			}
			this._frames = value;
		}
		
		private function timerHandler(e:Event):void{
			loopFrame();
		}
		
		//play anime automaticly
		public function loopAnime():void{
			timer.start();
		}
		
		public function stopAnime():void{
			timer.stop();
		}
		
		//show next frame
		public function loopFrame():void{
			if(this.frames==null||this.frames.length<2) return;
			var oldp:int = this.pFrame;
			if(pFrame==this.frames.length-1){
				pFrame=0;
			}else{
				pFrame++;
			}
			this.frames[oldp].visible = false;
			this.frames[pFrame].visible = true;
		} 
		
		public function rewindFrame():void{
			if(this.frames==null||this.frames.length<2) return;
			var oldp:int = this.pFrame;
			if(pFrame==0){
				pFrame=this.frames.length-1;
			}else{
				pFrame--;
			}
			this.frames[oldp].visible = false;
			this.frames[pFrame].visible = true;
		}
		
		public function get data():Object{return _data;}
		public function set data(value:Object):void{this._data = value;}
		
	}
}